<template>
  <div class="user-profile">
    <div class="container">
      <h1 class="page-title">个人资料</h1>
      
      <div v-if="loading" class="loading-container">
        <el-skeleton :rows="10" animated />
      </div>
      
      <template v-else>
        <el-row :gutter="20">
          <el-col :md="8" :xs="24">
            <div class="profile-card">
              <div class="avatar-container">
                <img :src="avatarUrl" :alt="currentUser.username" class="avatar">
                <div class="edit-avatar">
                  <el-upload
                    class="avatar-uploader"
                    action="#"
                    :show-file-list="false"
                    :before-upload="beforeAvatarUpload"
                  >
                    <i class="el-icon-camera"></i>
                  </el-upload>
                </div>
              </div>
              <h3 class="username">{{ currentUser.username }}</h3>
              <div class="user-role">
                <el-tag type="success" v-if="isAdmin">管理员</el-tag>
                <el-tag type="info" v-else>普通用户</el-tag>
              </div>
              <div class="user-info">
                <div class="info-item">
                  <i class="el-icon-time"></i>
                  <span>注册时间：{{ formatDate(currentUser.created_at) }}</span>
                </div>
                <div class="info-item">
                  <i class="el-icon-location"></i>
                  <span>所在地区：{{ profileData.region || '未设置' }}</span>
                </div>
              </div>
              
              <div class="profile-nav">
                <div 
                  class="nav-item" 
                  :class="{ active: activeTab === 'profile' }"
                  @click="activeTab = 'profile'"
                >
                  <i class="el-icon-user"></i>
                  <span>基本资料</span>
                </div>
                <div 
                  class="nav-item" 
                  :class="{ active: activeTab === 'security' }"
                  @click="activeTab = 'security'"
                >
                  <i class="el-icon-lock"></i>
                  <span>安全设置</span>
                </div>
              </div>
            </div>
          </el-col>
          
          <el-col :md="16" :xs="24">
            <div class="profile-content">
              <div v-if="activeTab === 'profile'">
                <div class="section-title">
                  <h2>基本资料</h2>
                  <p>您可以在此更新个人信息</p>
                </div>
                
                <el-form 
                  ref="profileForm" 
                  :model="profileData" 
                  :rules="profileRules" 
                  label-position="top"
                >
                  <el-row :gutter="20">
                    <el-col :md="12" :xs="24">
                      <el-form-item label="用户名" prop="username">
                        <el-input v-model="profileData.username" placeholder="请输入用户名" />
                      </el-form-item>
                    </el-col>
                    
                    <el-col :md="12" :xs="24">
                      <el-form-item label="真实姓名" prop="full_name">
                        <el-input v-model="profileData.full_name" placeholder="请输入真实姓名" />
                      </el-form-item>
                    </el-col>
                  </el-row>
                  
                  <el-row :gutter="20">
                    <el-col :md="12" :xs="24">
                      <el-form-item label="电子邮箱" prop="email">
                        <el-input v-model="profileData.email" placeholder="请输入电子邮箱" />
                      </el-form-item>
                    </el-col>
                    
                    <el-col :md="12" :xs="24">
                      <el-form-item label="手机号码" prop="phone">
                        <el-input v-model="profileData.phone" placeholder="请输入手机号码" />
                      </el-form-item>
                    </el-col>
                  </el-row>
                  
                  <el-form-item label="地址" prop="address">
                    <el-input 
                      type="textarea" 
                      v-model="profileData.address" 
                      placeholder="请输入详细地址"
                      :rows="3"
                    />
                  </el-form-item>
                  
                  <el-form-item>
                    <el-button 
                      type="primary" 
                      @click="updateProfile"
                      :loading="updatingProfile"
                    >
                      保存修改
                    </el-button>
                  </el-form-item>
                </el-form>
              </div>
              
              <div v-else-if="activeTab === 'security'">
                <div class="section-title">
                  <h2>安全设置</h2>
                  <p>您可以在此修改密码等安全相关设置</p>
                </div>
                
                <el-form 
                  ref="passwordForm" 
                  :model="passwordData" 
                  :rules="passwordRules" 
                  label-position="top"
                >
                  <el-form-item label="当前密码" prop="currentPassword">
                    <el-input 
                      v-model="passwordData.currentPassword" 
                      type="password" 
                      placeholder="请输入当前密码"
                      show-password
                    />
                  </el-form-item>
                  
                  <el-form-item label="新密码" prop="newPassword">
                    <el-input 
                      v-model="passwordData.newPassword" 
                      type="password" 
                      placeholder="请输入新密码"
                      show-password
                    />
                  </el-form-item>
                  
                  <el-form-item label="确认新密码" prop="confirmPassword">
                    <el-input 
                      v-model="passwordData.confirmPassword" 
                      type="password" 
                      placeholder="请再次输入新密码"
                      show-password
                    />
                  </el-form-item>
                  
                  <el-form-item>
                    <el-button 
                      type="primary" 
                      @click="changePassword"
                      :loading="changingPassword"
                    >
                      修改密码
                    </el-button>
                  </el-form-item>
                </el-form>
              </div>
            </div>
          </el-col>
        </el-row>
      </template>
    </div>
  </div>
</template>

<script>
import { mapGetters, mapActions } from 'vuex';

export default {
  name: 'UserProfile',
  data() {
    const validateConfirmPassword = (rule, value, callback) => {
      if (value !== this.passwordData.newPassword) {
        callback(new Error('两次输入的密码不一致'));
      } else {
        callback();
      }
    };
    
    return {
      activeTab: 'profile',
      updatingProfile: false,
      changingPassword: false,
      
      profileData: {
        username: '',
        full_name: '',
        email: '',
        phone: '',
        address: ''
      },
      
      passwordData: {
        currentPassword: '',
        newPassword: '',
        confirmPassword: ''
      },
      
      profileRules: {
        username: [
          { required: true, message: '请输入用户名', trigger: 'blur' },
          { min: 2, max: 20, message: '长度在 2 到 20 个字符', trigger: 'blur' }
        ],
        full_name: [
          { required: true, message: '请输入真实姓名', trigger: 'blur' },
          { max: 100, message: '长度不能超过 100 个字符', trigger: 'blur' }
        ],
        email: [
          { required: true, message: '请输入邮箱地址', trigger: 'blur' },
          { type: 'email', message: '请输入正确的邮箱地址', trigger: 'blur' }
        ],
        phone: [
          { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号码', trigger: 'blur' }
        ],
        address: [
          { max: 255, message: '地址长度不能超过 255 个字符', trigger: 'blur' }
        ]
      },
      
      passwordRules: {
        currentPassword: [
          { required: true, message: '请输入当前密码', trigger: 'blur' },
          { min: 6, message: '密码长度不能小于 6 个字符', trigger: 'blur' }
        ],
        newPassword: [
          { required: true, message: '请输入新密码', trigger: 'blur' },
          { min: 6, message: '密码长度不能小于 6 个字符', trigger: 'blur' }
        ],
        confirmPassword: [
          { required: true, message: '请再次输入新密码', trigger: 'blur' },
          { validator: validateConfirmPassword, trigger: 'blur' }
        ]
      },
      
      regionOptions: [
        {
          value: 'beijing',
          label: '北京',
          children: [
            { value: 'chaoyang', label: '朝阳区' },
            { value: 'haidian', label: '海淀区' },
            { value: 'dongcheng', label: '东城区' },
            { value: 'xicheng', label: '西城区' }
          ]
        },
        {
          value: 'shanghai',
          label: '上海',
          children: [
            { value: 'pudong', label: '浦东新区' },
            { value: 'huangpu', label: '黄浦区' },
            { value: 'jing_an', label: '静安区' },
            { value: 'xuhui', label: '徐汇区' }
          ]
        }
      ]
    };
  },
  computed: {
    ...mapGetters({
      currentUser: 'auth/currentUser',
      isAdmin: 'auth/isAdmin',
      loading: 'isLoading'
    }),
    avatarUrl() {
      return this.currentUser.avatar_url 
        ? `${process.env.VUE_APP_API_URL}${this.currentUser.avatar_url}`
        : 'https://cube.elemecdn.com/3/7c/3ea6beec64369c2642b92c6726f1epng.png';
    }
  },
  created() {
    // 初始化表单数据
    this.initProfileData();
  },
  methods: {
    ...mapActions({
      updateProfileAction: 'auth/updateProfile',
      changePasswordAction: 'auth/changePassword'
    }),
    initProfileData() {
      const user = this.currentUser;
      if (user) {
        this.profileData = {
          username: user.username || '',
          full_name: user.full_name || '',
          email: user.email || '',
          phone: user.phone || '',
          address: user.address || ''
        };
      }
    },
    formatDate(dateString) {
      if (!dateString) return '未知';
      const date = new Date(dateString);
      return date.toLocaleDateString('zh-CN');
    },
    beforeAvatarUpload(file) {
      const isJPG = file.type === 'image/jpeg';
      const isPNG = file.type === 'image/png';
      const isLt2M = file.size / 1024 / 1024 < 2;

      if (!isJPG && !isPNG) {
        this.$message.error('头像图片只能是 JPG 或 PNG 格式!');
        return false;
      }
      
      if (!isLt2M) {
        this.$message.error('头像图片大小不能超过 2MB!');
        return false;
      }
      
      // 这里应该上传头像，但由于没有实际的后端，我们只是显示一条成功消息
      this.$message.success('头像上传成功！');
      return false; // 阻止默认上传行为
    },
    async updateProfile() {
      try {
        await this.$refs.profileForm.validate();
        
        this.updatingProfile = true;
        
        // 添加更新时间
        const updateData = {
          ...this.profileData,
          updated_at: new Date().toISOString()
        };
        
        const success = await this.updateProfileAction(updateData);
        
        if (success) {
          this.$message({
            type: 'success',
            message: '个人资料更新成功'
          });
        }
      } catch (error) {
        console.error('更新个人资料失败', error);
        this.$message.error('更新个人资料失败，请重试');
      } finally {
        this.updatingProfile = false;
      }
    },
    async changePassword() {
      try {
        await this.$refs.passwordForm.validate();
        
        this.changingPassword = true;
        
        const success = await this.changePasswordAction({
          current_password: this.passwordData.currentPassword,
          new_password: this.passwordData.newPassword
        });
        
        if (success) {
          this.$message({
            type: 'success',
            message: '密码修改成功'
          });
          
          // 清空表单
          this.passwordData = {
            currentPassword: '',
            newPassword: '',
            confirmPassword: ''
          };
          
          // 重置表单验证
          this.$refs.passwordForm.resetFields();
        }
      } catch (error) {
        console.error('表单验证失败', error);
      } finally {
        this.changingPassword = false;
      }
    }
  }
}
</script>

<style lang="scss" scoped>
@use "sass:color";

.user-profile {
  padding: 40px 0;
}

.loading-container {
  min-height: 400px;
  display: flex;
  justify-content: center;
  align-items: center;
}

.profile-card {
  background-color: #fff;
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
  padding: 20px;
  text-align: center;
  margin-bottom: 20px;
}

.avatar-container {
  position: relative;
  width: 100px;
  height: 100px;
  margin: 0 auto 20px;
}

.avatar {
  width: 100%;
  height: 100%;
  border-radius: 50%;
  object-fit: cover;
}

.edit-avatar {
  position: absolute;
  right: 0;
  bottom: 0;
  width: 30px;
  height: 30px;
  border-radius: 50%;
  background-color: var(--primary-color);
  color: white;
  display: flex;
  align-items: center;
  justify-content: center;
  cursor: pointer;
  
  &:hover {
    background-color: color.adjust(#42b983, $lightness: -10%);
  }
  
  .el-icon-camera {
    font-size: 16px;
  }
}

.username {
  font-size: 1.5rem;
  margin-bottom: 10px;
  color: var(--secondary-color);
}

.user-role {
  margin-bottom: 20px;
}

.user-info {
  text-align: left;
  margin-bottom: 20px;
  
  .info-item {
    display: flex;
    align-items: center;
    margin-bottom: 10px;
    color: var(--gray-color);
    
    i {
      margin-right: 10px;
    }
  }
}

.profile-nav {
  border-top: 1px solid #eee;
  padding-top: 20px;
  
  .nav-item {
    display: flex;
    align-items: center;
    padding: 10px;
    cursor: pointer;
    border-radius: 4px;
    transition: all 0.3s;
    
    i {
      margin-right: 10px;
    }
    
    &:hover {
      background-color: #f5f7fa;
    }
    
    &.active {
      background-color: #ecf5ff;
      color: var(--primary-color);
    }
  }
}

.profile-content {
  background-color: #fff;
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
  padding: 20px;
}

.section-title {
  margin-bottom: 20px;
  
  h2 {
    margin-bottom: 5px;
    color: var(--secondary-color);
  }
  
  p {
    color: var(--gray-color);
    font-size: 0.9rem;
  }
}

@media (max-width: 768px) {
  .profile-card {
    margin-bottom: 20px;
  }
}
</style> 